package com.ciaojian.websocket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.base.annotation.ApiIdempotent;
import com.ciaojian.core.enums.business.OrderStatusEnum;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.PresentGiftRecord;
import com.ciaojian.core.util.Result;
import com.ciaojian.websocket.server.MyWebSocket;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Atlakyn
 */
@Log4j2(topic = "business")
@RestController
@RequestMapping
public class WebSocketController {
    private MyWebSocket myWebSocket;

    @Autowired
    public void setMyWebSocket(MyWebSocket myWebSocket) {
        this.myWebSocket = myWebSocket;
    }

    @ApiOperation("送礼")
    @PostMapping("/gift/present/{orderId}")
    public Result presentGift(@PathVariable Integer orderId) {
        Order order = new Order().selectById(orderId);
        Assert.notNull(order, "请选择订单");
        Assert.isTrue(order.getStatus().equals(OrderStatusEnum.paid) || order.getStatus().equals(OrderStatusEnum.complete), "订单未完成");
        Integer count = new PresentGiftRecord()
                .selectCount(new QueryWrapper<PresentGiftRecord>().eq("order_id", orderId));
        Assert.isTrue(count == 0, "此订单已送过");

        Map<String, Object> data = new HashMap<>(2);
        data.put("orderId", orderId);
        data.put("fromId", order.getWorkerId());
        Map<String, Object> map = new HashMap<>(2);
        map.put("message", "是否接收礼物?");
        map.put("data", data);
        try {
            myWebSocket.sendMessageTo(new ObjectMapper().writeValueAsString(map), order.getUserId());
            log.info(">>>{}送礼给{},订单是{}>>>", order.getWorkerId(), order.getUserId(), orderId);
        } catch (NullPointerException e) {
            return Result.error("用户不在线");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.info(">>>presentGift,Json 转换异常:{}>>>", e.getMessage());
            return Result.error("发送失败");
        }
        return Result.ok();
    }

    @ApiOperation("处理礼物")
    @ApiIdempotent
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/gift/handle")
    public Result handleGift(@RequestBody PresentGiftRecord presentGiftRecord) {
        QueryWrapper<PresentGiftRecord> queryWrapper = new QueryWrapper<PresentGiftRecord>()
                .eq("order_id", presentGiftRecord.getOrderId())
                .last("limit 1");
        Integer count = new PresentGiftRecord().selectCount(queryWrapper);
        Assert.isTrue(count == 0, "已处理过此订单");
        presentGiftRecord.insert();
        log.info(">>>{}接受了{}的礼物,订单是{}>>>", presentGiftRecord.getReceiveId(), presentGiftRecord.getFromId(), presentGiftRecord.getOrderId());
        return Result.ok();
    }
}
